package org.example.service;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.R.R;
import org.example.entity.dto.AddAddressBookDto;
import org.example.entity.po.AddressBookPO;
import org.example.entity.vo.AddressBookVO;
import org.example.mapper.AddressBookMapper;
import org.example.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    public R add(AddAddressBookDto dto) {
        String msg = "";
        if (dto.getId()==null){
            AddressBookPO po = new AddressBookPO();
            BeanUtils.copyProperties(dto,po);
            po.setId(IdUtil.getSnowflakeNextId());
            po.setCreateTime(TimeUtils.getCurrentDate());
            addressBookMapper.insert(po);
            msg = "添加成功!";
        }else {
            AddressBookVO addressBookVO = addressBookMapper.findOne(dto.getId());
            if (addressBookVO==null){
                return R.error("该通讯录记录不存在");
            }
            addressBookMapper.delete(dto.getId());
            AddressBookPO po = new AddressBookPO();
            BeanUtils.copyProperties(dto,po);
            po.setCreateTime(addressBookVO.getCreateTime());
            addressBookMapper.insert(po);
            msg = "编辑成功!";
        }

        return R.success(msg);
    }


    public R delete(Long id) {
        addressBookMapper.delete(id);
        return R.success("删除成功!");
    }

    public R detail(Long id) {
        AddressBookVO one = addressBookMapper.findOne(id);
        return R.success("获取成功!").setData(one);
    }

    public R list() {
        List<AddressBookVO> list = addressBookMapper.list();
        return R.success("获取成功!").setData(list);
    }
}
